package com.example.tally;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.tally.DataBase.AccountBean;
import com.example.tally.DataBase.DBManager;
import com.example.tally.adapter.AccountAdapter;
import com.example.tally.utils.BudgetDialog;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
    ListView todayLv;   //展示今日收支情况的ListView
    ImageView searchIv,moreBtn;
    Button editBtn;
    NavigationView navView;
    DrawerLayout drawerLayout;
    //声明数据源
    List<AccountBean> mDatas;
    AccountAdapter adapter;
    int year,month,day;
    //头布局相关控件
    View headerView;
    TextView topOutTv,topInTv,topBudGetTv,topConTv;
    ImageView topShowIv;
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTime();
        initView();
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        //添加ListView的头布局
        addLvHeaderView();

        mDatas = new ArrayList<>();
        //设置适配器，加载每一行的数据到列表ListView中
        adapter = new AccountAdapter(this, mDatas);
        todayLv.setAdapter(adapter);

    }

//    初始化自带的View的方法
    private void initView() {
        todayLv = findViewById(R.id.main_lv);
        editBtn = findViewById(R.id.main_btn_edit);
        moreBtn = findViewById(R.id.main_btn_more);
        searchIv = findViewById(R.id.main_iv_search);
        //左侧隐藏的NavigationView布局
        navView = (NavigationView) findViewById(R.id.nav_view);
        navView.setNavigationItemSelectedListener(this);   //nva菜单的Item点击事件钮监听
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setOnClickListener(this);
        editBtn.setOnClickListener(this);
        moreBtn.setOnClickListener(this);
        searchIv.setOnClickListener(this);
    }

//    给ListView添加头布局的方法
    private void addLvHeaderView() {
        //将布局转换成View对象
        headerView = getLayoutInflater().inflate(R.layout.item_mainlv_top, null);
        todayLv.addHeaderView(headerView);
        //绑定头布局的控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_mainlv_top_tv_in);
        topBudGetTv = headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv_day);
        topShowIv = headerView.findViewById(R.id.item_mainlv_top_iv_hide);
        topBudGetTv.setOnClickListener(this);
        headerView.setOnClickListener(this);
        topShowIv.setOnClickListener(this);
        setLvLongClickListener();

    }

//    设置ListView的长按事件
    private void setLvLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {   //点击了头布局
                    return false;
                }
                int pos = position - 1;
                AccountBean clickBean = mDatas.get(pos);    //获取正在被点击的这条信息
                //弹出提示用户是否确认删除的对话框
                showDelateItemDialog(clickBean);
                return false;
            }
        });
    }

//    弹出提示用户是否确定删除某一条记录的对话框
    private void showDelateItemDialog(final AccountBean clickBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息").setMessage("确定要删除这条记录吗？")
                .setNegativeButton("取消",null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int click_id = clickBean.getId();
                        //执行删除的操作
                        DBManager.deleteItemFromAccountTbById(click_id);
                        mDatas.remove(clickBean);    //实时刷新，移除集合中的对象
                        adapter.notifyDataSetChanged();   //提示适配器更新数据
                        setTopTvShow();   //改变头布局TextView显示的内容
                    }
                });
        builder.create().show();   //显示对话框
    }

    //    获取今日的具体时间
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    //当Activity获取焦点时调用的方法
    @Override
    protected void onResume() {
        super.onResume();
        loadDBData();
        setTopTvShow();
    }

//    设置头布局当中文本内容的显示
    private void setTopTvShow() {
        //获取今日支出和收入的总金额，显示在View当中
        float incomeOneDay = DBManager.getSumMoneyOneDay(year, month, day, 1);
        float outcomeOneDay = DBManager.getSumMoneyOneDay(year, month, day, 0);
        String infoOneDay = "今日支出 ￥"+outcomeOneDay+"  收入 ￥"+incomeOneDay;
        topConTv.setText(infoOneDay);

        //获取本月支出和收入的总金额，显示在View当中
        float incomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 1);
        float outcomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 0);
        topInTv.setText("￥"+incomeOneMonth);
        topOutTv.setText("￥"+outcomeOneMonth);

        //设置显示预算剩余
        float budget_money = preferences.getFloat("budget_money", 0);  //获取预算
        if (budget_money == 0){
            topBudGetTv.setText("￥ 0");
        }else{
            float syMoney = budget_money - outcomeOneMonth;
            topBudGetTv.setText("￥"+syMoney);
        }
    }

    private void loadDBData() {
        List<AccountBean> list = DBManager.getAccountListOneDayFromAccountTb(year, month, day);   //数据库中查找出来的今天的支出收入信息
        mDatas.clear();   //先清空数据
        mDatas.addAll(list);   //添加新数据
        adapter.notifyDataSetChanged();   //提示adapter更新
    }

//    侧滑栏导航item点击事件监听
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        Intent intent = new Intent();
        switch (menuItem.getItemId()){
            case R.id.fragment_record:
                intent.setClass(this, HistoryActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(GravityCompat.START);   //关闭侧滑栏
                break;
            case R.id.fragment_info:
                intent.setClass(this, MonthChartActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(GravityCompat.START);
                break;
            case R.id.fragment_about:
                intent.setClass(this, AboutActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(GravityCompat.START);
                break;
            case R.id.fragment_setting:
                intent.setClass(this, SettingActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(GravityCompat.START);
                break;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_iv_search:
                Intent intent = new Intent(this, SearchActivity.class);   //跳转界面
                startActivity(intent);
                break;
            case R.id.main_btn_edit:
                Intent intent1 = new Intent(this, RecordActivity.class);   //跳转界面
                startActivity(intent1);
                break;
            case R.id.main_btn_more:
                drawerLayout.openDrawer(GravityCompat.START);   //设置左边菜单栏显示出来
                break;
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
            case R.id.item_mainlv_top_iv_hide:
                //切换TextView明文和密文，即隐藏和显示
                toggleShow();
                break;
            case R.id.item_mainlv_top_tv4:
                //查看图表分析按钮
                Intent intent2 = new Intent(this,MonthChartActivity.class);    //跳转界面
                startActivity(intent2);
                break;
        }
    }

//    显示预算设置的对话
    private void showBudgetDialog() {
        BudgetDialog dialog = new BudgetDialog(this);
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(Float money) {
                //将预算金额写入到共享参数中，进行存储
                SharedPreferences.Editor editor = preferences.edit();
                editor.putFloat("budget_money",money);
                editor.commit();

                //计算剩余余额
                float outcomeOneMonth = DBManager.getSumMoneyOneMonth(year, month, 0);
                float syMoney = money - outcomeOneMonth;   //预算剩余=预算金额-支出
                topBudGetTv.setText("￥"+syMoney);
            }
        });
    }

    boolean isShow = true;   //是否显示
//    点击头布局眼睛时，切换隐藏和显示两种状态
    private void toggleShow() {
        if (isShow){   //显示转隐藏
            PasswordTransformationMethod passwordMethod = PasswordTransformationMethod.getInstance();   //得到密码对象
            topInTv.setTransformationMethod(passwordMethod);    //设置隐藏
            topOutTv.setTransformationMethod(passwordMethod);    //设置隐藏
            topBudGetTv.setTransformationMethod(passwordMethod);    //设置隐藏
            topShowIv.setImageResource(R.mipmap.ih_hide);
            isShow = false;   //设置标志位为隐藏状态
        }else{    //隐藏转显示
            HideReturnsTransformationMethod hideMethod = HideReturnsTransformationMethod.getInstance();   //得到原始对象
            topInTv.setTransformationMethod(hideMethod);    //设置显示
            topOutTv.setTransformationMethod(hideMethod);    //设置显示
            topBudGetTv.setTransformationMethod(hideMethod);    //设置显示
            topShowIv.setImageResource(R.mipmap.ih_show);
            isShow = true;   //设置标志位为显示状态
        }
    }
}